package com.kuaimacode.kframework.component;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.kuaimacode.kframework.exception.ErrorEnum;
import com.kuaimacode.kframework.exception.ServerInternalErrorException;
import com.kuaimacode.kframework.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author qinyong
 * @Title:
 * @Package com.kuaimacode.kframework.api.component
 * @Description: created by IntelliJ IDEA
 * @date 2019-03-13 21:39
 */
@Slf4j
@Component
public class SmsSendService {

    @Value("${aliyuns.api.keyid}")
    private String accessKeyId;
    @Value("${aliyuns.api.secret}")
    private String accessKeySecret;
    @Value("${sms.sign.name}")
    private String signName;
    @Value("${sms.login.template.code}")
    private String smsLoginTempCode;
    @Value("${spring.profiles.active}")
    private String enviroment;
    @Autowired
    private SmsRecordService smsRecordService;

    /**
     * 发送短信
     *
     * @param phoneNumber    支持对多个手机号码发送短信，手机号码之间以英文逗号（,）分隔。上限为1000个手机号码
     * @param templateCode   短信模板ID。请在控制台模板管理页面模板CODE一列查看。
     * @param templateParams 短信模板变量对应的实际值，JSON格式。{"code":"1111"}
     * @return
     */
    public boolean sendSms(String phoneNumber, String templateCode, Map<String, Object> templateParams) {
        DefaultProfile profile = DefaultProfile.getProfile("default", accessKeyId, accessKeySecret);

        IAcsClient client = new DefaultAcsClient(profile);
        // 创建API请求并设置参数
        CommonRequest request = new CommonRequest();
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        if (!CollectionUtils.isEmpty(templateParams)) {
            request.putQueryParameter("TemplateParam", JSONObject.toJSONString(templateParams));
        }
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        //设置连接超时为5000毫秒
        request.setConnectTimeout(5000);
        //设置读超时为5000毫秒
        request.setReadTimeout(5000);
        CommonResponse response;
        try {
            response = client.getCommonResponse(request);
            JSONObject jsonObject = JSONObject.parseObject(response.getData());
            String code = jsonObject.getString("Code");
            if ("OK".equals(code)) {
                return true;
            } else if ("isv.BUSINESS_LIMIT_CONTROL".equals(code)){
                log.error("mobile: {}, templateCode: {}, 发送短信失败结果, [{}]", phoneNumber, templateCode, response.getData());
                throw new ServerInternalErrorException(ErrorEnum.SMS_SEND_FREQUENTLY);
            }
            log.error("mobile: {}, templateCode: {}, 发送短信失败结果, [{}]", phoneNumber, templateCode, response.getData());
        } catch (ClientException e) {
            log.error("发送短信失败", e);
        }
        return false;
    }

    /**
     * 发送登陆时的验证码
     * @param phoneNumber
     * @return
     */
    public boolean sendLoginVerifyCode(String phoneNumber) {
        String verifyCode = StringUtil.generateRandom(4);
        Map<String, Object> params = new HashMap<>();
        params.put("code", verifyCode);
        //开发环境模拟发送成功
        if (sendSms(phoneNumber, smsLoginTempCode, params)) {
            smsRecordService.saveRecord(phoneNumber, verifyCode);
            return true;
        }
        return false;
    }

    /**
     * 发送同意申请提现短信
     * @return
     */
    public boolean sendAgreeWithdrawalMsg(String phone, Map<String, Object> templateParams) {
        return sendSms(phone, "SMS_166377396", templateParams);
    }

    /**
     * 发送拒绝申请提现短信
     * @return
     */
    public boolean sendRejectWithdrawalMsg(String phone, Map<String, Object> templateParams) {
        return sendSms(phone, "SMS_166377438", templateParams);
    }


    /**
     * 发送收货验证码
     * @return
     */
    public boolean sendRecVerifyCode(String phone, Map<String, Object> templateParams) {
        return sendSms(phone, "SMS_169895780", templateParams);
    }

}
